package tom.webmvc.controller;

import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import tom.webmvc.event.MsgEvent;
import tom.webmvc.service.SseService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Set;

/**
 * spring-mvc中对sse的支持
 * SSE Server Sent Event
 * @author ZHUFEIFEI
 */
@RestController
public class SseController {
    @Autowired
    private ApplicationContext context;

    @Autowired
    private SseService sseService;

    @GetMapping("/sse")
    public SseEmitter emitter() {
        //客户端超时15秒
        SseEmitter sseEmitter = new SseEmitter(60 * 1000L);
        this.sseService.add(sseEmitter);
        return sseEmitter;
    }

    /**
     * 注解形式的sse , 支持text/event-stream application/stream+json
     * 每秒发送一条数据, 发送完毕以后，客户端就需要重新连接
     * @return
     */
    @GetMapping(value = "/time", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public String time() throws InterruptedException {
        Thread.sleep(1000L);
        //结尾必须\n\n表示一个数据发送结束
        return "data: time(" + SimpleDateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime())
                + ")\n\n";
    }

    @GetMapping("/msg/{msg}")
    public ResponseEntity<Object> saveData(@PathVariable("msg") String msg) {
        this.context.publishEvent(new MsgEvent(msg));
        return ResponseEntity.ok("msg received!");
    }

}
